/**
 * fulihui.com Inc.
 * Copyright (c) 2015-2016 All Rights Reserved.
 */
package com.fulihui.integral.core.strategy.business;

import com.fulihui.integral.core.common.constants.ExtParamKeys;
import com.fulihui.integral.core.common.constants.RuleKeys;
import com.fulihui.integral.core.common.entity.RuleData;
import com.fulihui.integral.core.dal.dataobj.ISAccountDetail;
import com.fulihui.integral.core.dal.dataobj.ISAccountDetailExample;
import com.fulihui.integral.core.enums.ISChannelType;
import com.fulihui.integral.core.strategy.StrategyParam;
import com.fulihui.integral.core.strategy.StrategyResult;
import org.near.toolkit.common.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * 老版本更新积分策略
 *
 * @author yunfeng.li
 * @version $Id: v 0.1 2017年04月19日 19:34 yunfeng.li Exp $
 */
@Component("updateVersionStrategy")
public class UpdateVersionStrategy extends IntegralAbstractStrategy {
    @Override
    public StrategyResult calculate(StrategyParam param) {
        StrategyResult result = new StrategyResult();
        Map<String, String> extParam = param.getExtParam();
        String userId = param.getUserId();
        String version = extParam.get(ExtParamKeys.EXT_VERSION);
        Map<String, RuleData> rule = param.getRule();
        if (rule.containsKey(RuleKeys.UPDATE_VERSION)) {
            RuleData ruleData = rule.get(RuleKeys.UPDATE_VERSION);
            String value = ruleData.getValue();
            if (StringUtil.isNotBlank(value)) {
                ISAccountDetailExample example = new ISAccountDetailExample();
                ISAccountDetailExample.Criteria criteria = example.createCriteria();
                criteria.andUserIdEqualTo(userId);
                criteria.andChannelEqualTo(ISChannelType.UPDATE_VERSION.getCode());
                criteria.andOutTradeNoEqualTo(version);
                List<ISAccountDetail> isAccountDetails = iSAccountDetailMapper.selectByExample(example);
                if (CollectionUtils.isEmpty(isAccountDetails)) {
                    result.setAmount(Long.valueOf(value));
                    return result;
                }
            }
        }
        return result;
    }

    @Override
    public ISChannelType getFlag() {
        return ISChannelType.UPDATE_VERSION;
    }
}
